import { HttpResponse } from './httpClient';
import { API_BASE_URL } from './apiConfig';

// 模拟网络延迟
const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));

// 定义Mock处理器接口
export interface MockHandler {
  handleRequest<T>(
    url: string,
    options?: RequestInit,
  ): Promise<HttpResponse<T> | null>;
}

// 动态导入user mock处理器
async function getUserMockHandler(): Promise<MockHandler | null> {
  try {
    const module = await import('../mocks/users');
    return module.userMockHandler || null;
  } catch (error) {
    console.warn('Failed to load user mock handler:', error);
    return null;
  }
}

export class MockService {
  // 是否启用mock服务
  static enabled = false;

  // 存储各模块的mock处理器
  private static handlers: Map<string, () => Promise<MockHandler | null>> =
    new Map([['users', getUserMockHandler]]);

  // 注册mock处理器
  static registerHandler(
    moduleName: string,
    loader: () => Promise<MockHandler | null>,
  ) {
    this.handlers.set(moduleName, loader);
  }

  // 拦截请求并返回模拟数据
  static async intercept<T>(
    url: string,
    options?: RequestInit,
  ): Promise<HttpResponse<T> | null> {
    // 如果未启用mock服务，不拦截请求
    if (!this.enabled) {
      console.log('MockService not enabled, skipping interception');
      return null;
    }

    // 模拟网络延迟
    await delay(300 + Math.random() * 700); // 300-1000ms的随机延迟

    // 解析URL
    const cleanUrl = url.startsWith('http')
      ? url.replace(API_BASE_URL, '')
      : url;

    console.log('MockService intercepting request:', cleanUrl);

    // 尝试使用各模块的处理器处理请求
    for (const [moduleName, loader] of this.handlers) {
      try {
        const handler = await loader();
        if (handler) {
          const response = await handler.handleRequest<T>(cleanUrl, options);
          if (response) {
            console.log(
              `Request handled by ${moduleName} mock handler:`,
              cleanUrl,
              response,
            );
            return response;
          }
        }
      } catch (error) {
        console.warn(`Error in mock handler for module ${moduleName}:`, error);
      }
    }

    // 对于未处理的URL，返回null表示不拦截
    console.log('No mock handler found for URL:', cleanUrl);
    return null;
  }
}

// 初始化时根据配置决定是否启用mock服务
import { AppConfig } from '../config';
MockService.enabled = AppConfig.USE_MOCK_DATA;
console.log('MockService enabled status:', MockService.enabled);
